import MenuManager from "../LoadScene/MenuManager";
import Npc from "./Npc";
import Player from "./Player";
import CameraFollow from "./CameraFollow";
import DirController from "../LoadScene/DirController";
import PlotManager from "./PlotManager";
import DialogPanel from "../LoadScene/DialogPanel";
import Door from "./Door";
import mapItem from "./mapItem";

const {ccclass, property} = cc._decorator;

@ccclass
export default class MapManager extends cc.Component {
    /** 地图名称 */
    private mapName:string;   
    /** 常驻节点 菜单管理器 */
    public menuManager:MenuManager; 

    /** 地图-点组 */
    private pointGroup:cc.Node;
    /** 地图-路径组 */
    private pathGroup:cc.Node;
    /** 地图-门组 */
    private doorGroup:cc.Node;
    /** 地图-物品组 */
    private itemGroup:cc.Node;

    /** 地图遮罩层 */
    private mask:cc.Node;

  

    /** 摄像机跟随组件 */
    cameraFollow:CameraFollow

    /** 方向盘控制组件 */
    dirController:DirController;

    /** 剧本控制组件 */
    plotManager:PlotManager;
    /** 对话层控制组件 */
    dialogPanel:DialogPanel;

    /** Npc的预制体 */   
    npcPrefab:cc.Prefab=null
    /** Player的预制体 */   
    playerPrefab:cc.Prefab=null





    onLoad () {
        var scene = this.node.parent;


        cc.log(scene,scene.getScale());

        scene.scaleX=scene.scaleY = 1;

        this.npcPrefab = cc.loader.getRes("Prefab/npc",cc.Prefab);
        this.playerPrefab = cc.loader.getRes("Prefab/player",cc.Prefab);
        this.cameraFollow = cc.find("Camera").getComponent(CameraFollow);
        this.plotManager = this.getComponent(PlotManager);
      


        this.node.setContentSize(this.node.getChildByName("map").getContentSize());
        this.pointGroup = this.node.getChildByName("pointGroup");                
        this.pathGroup = this.node.getChildByName("pathGroup");
        this.doorGroup = this.node.getChildByName("doorGroup");
        this.itemGroup = this.node.getChildByName("itemGroup");
        this.mask = this.node.getChildByName("mask");
        if(this.mask){
            this.mask.zIndex = 9999;
        }
        
    
        this.menuManager = cc.find("MenuRoot").getComponent(MenuManager);       
        this.dirController = this.menuManager.node.getChildByName("dirController").getComponent(DirController);
        this.dialogPanel = this.menuManager.node.getChildByName("DialogPanel").getComponent(DialogPanel);

        
    }


    start(){
        
        this.mapName = QM.game.map;
        var mapDat = QM.game.getMapDat();
                
        if(!mapDat){
            //加载当前的地图初始数据
            cc.loader.loadRes("MapDat/"+this.mapName,cc.JsonAsset,(err,dat)=>{
                QM.game.setMapDat(dat.json);
                this.parseMapDat();
            })
        }else{            
            this.parseMapDat();
        }        
    }


    /**
     * 解析地图数据
     */
    parseMapDat(){
        this.initPlayer();

        /** 初始化Npc */
        this.initNpc();
                      
        /** 初始化门 */
        this.initDoor();
        /** 初始化地图上的物品 */
        this.initMapItem();

        /** 解析出场剧本 */
        var mapDat = QM.game.getMapDat();        
        this.showUI();    
        if(mapDat && mapDat.plot){
            this.plotManager.parse(mapDat.plot);
        }        
    }

    /**
     * 初始化队友
     */
    initPlayer(){
        var players = QM.game.getTeam();
        if(!players || !players.length) return;
        var tempP:Player;
        players.forEach(player=>{
            var node = cc.instantiate(this.playerPrefab);
            node.parent = this.node;
            var playerCom = node.getComponent(Player)
            playerCom.player = player;                  
            if(player.number==1){
                this.cameraFollow.follow(node,this.node.getContentSize() )                
                this.dirController.target = playerCom;    
                if(QM.game.door){                 
                    //查找门前点
                    var door = this.findDoor(QM.game.door);
                    node.position = door.gatePisition;                    
                    playerCom.dir = door.dir;
                }
            }
            if(tempP){
                tempP.follower = playerCom;
            }
            tempP = playerCom;
        })

    }

    /** 初始化Npc */
    initNpc(){
        var mapDat = QM.game.getMapDat();        
        if(!mapDat || !mapDat.npc) return;
        var npcs = mapDat.npc;
        npcs.forEach(npc => {            
            var node = cc.instantiate(this.npcPrefab);
            node.position = this.findPoint(npc.point);
            node.parent = this.node;            
            var npcCom = node.getComponent(Npc)
            npcCom.npc = npc;
            
            if(npc.path){            
                npcCom.path = this.findPath(npc.path);
            }
        });
    }

    /** 移除地图上的npc */
    removeNpc(name:string){
        var node = this.node.getChildByName(name);
        if(node){
            node.parent = null;
        }

        var mapDat = QM.game.getMapDat();
        var npcs = mapDat.npc;
        for(var i=0;i<npcs.length;i++){
            if(npcs[i].name==name){
                npcs.splice(i,1);
                break;
            }
        }
    }


    /** 初始化门 */
    initDoor(){
        var mapDat = QM.game.getMapDat();        
        if(!mapDat || !mapDat.door)return;
        var doors = mapDat.door;
        doors.forEach(door=>{
            var doorCom = this.findDoor(door.name);
            doorCom.reset(door);
        })
    }

    /** 初始化地图上的物品 */
    initMapItem(){
        var mapDat = QM.game.getMapDat();
        if(!mapDat || !mapDat.item) return;
        var items = mapDat.item;
        items.forEach(item=>{
            this.addMapItem(item,false)
        })
    }

    /** 往地图上添加物品 */
    addMapItem(item:QM.Item,updateDat=true){
        var node = new cc.Node();
        node.parent = this.node;
        node.setPosition(this.findPoint(item.point));
        var mapCom:mapItem = node.addComponent(mapItem);
        mapCom.setData(item);
        if(updateDat){
            //给地图数据加上物品信息
            var mapDat = QM.game.getMapDat();
            if(mapDat.item){
                mapDat.item.push(item);
            }else{
                mapDat.item = [item];
            }
        }
        
    }

    //查找地图点
    findPoint(name:string){
        var node = this.pointGroup.getChildByName(name);
        if(!node){
            cc.log(name+"点不存在")
            return 
        }
        return node.position;
    }

    //查找地图上的路径
    findPath(name:string):cc.Vec2[]{
        var path = this.pathGroup.getChildByName(name);
        if(!path){
            cc.log(name+"路径不存在");
            return;
        }
        var res = [];
        for(var i=0;i<path.childrenCount;i++){
            res.push(path.children[i].position)            
        }
        return res;        
    }

    /** 查找门 */
    findDoor(name:string):Door{
        var door = this.doorGroup.getChildByName(name).getComponent(Door);
        return door;  
    }

    showUI(){                
        QM.game.state = QM.gameState.normal;        
        this.menuManager.dirController.node.active = true;
        this.menuManager.menuNode.active = true;        
        cc.director.getCollisionManager().enabled = true;
    }
    hideUI(){                
        QM.game.state = QM.gameState.Plot;        
        this.menuManager.dirController.node.active = false;
        this.menuManager.menuNode.active = false;
        cc.director.getCollisionManager().enabled = false;
    }
}
